package com.mindskip.xzs.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.component.QywxComponent;
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.domain.enums.QywxMsgType;
import com.mindskip.xzs.repository.NewUserMapper;
import com.mindskip.xzs.repository.QywxMessageMapper;
import com.mindskip.xzs.repository.QywxMessageUserMapper;
import com.mindskip.xzs.service.MessageService;
import com.mindskip.xzs.service.NewUserService;
import com.mindskip.xzs.service.QywxMessageUserService;
import com.mindskip.xzs.service.UserService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.message.*;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.viewmodel.wx.student.qywx.MiniProgramNotice;
import com.mindskip.xzs.viewmodel.wx.student.qywx.TextCardNotice;
import com.mindskip.xzs.viewmodel.wx.student.qywx.TextNotice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController("AdminMessageController")
@RequestMapping(value = "/api/admin/message")
public class MessageController extends BaseApiController {

    private final MessageService messageService;
    private final UserService userService;
    @Resource
    private QywxComponent qywxComponent;
    @Resource
    private QywxMessageMapper qywxMessageMapper;
    @Resource
    private QywxMessageUserService qywxMessageUserService;

    /**
     * agentid
     * 每个应用都有唯一的agentid。在管理后台->“应用与小程序”->“应用”，点进某个应用，即可看到agentid。
     */
    @Value("${qywx.agentId}")
    private Long agentId;

    @Autowired
    public MessageController(MessageService messageService, UserService userService) {
        this.messageService = messageService;
        this.userService = userService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<MessageResponseVM>> pageList(@RequestBody MessagePageRequestVM model) {
        PageInfo<Message> pageInfo = messageService.page(model);
        List<Integer> ids = pageInfo.getList().stream().map(d -> d.getId()).collect(Collectors.toList());
        List<MessageUser> messageUsers = ids.size() == 0 ? null : messageService.selectByMessageIds(ids);
        PageInfo<MessageResponseVM> page = PageInfoHelper.copyMap(pageInfo, m -> {
            MessageResponseVM vm = modelMapper.map(m, MessageResponseVM.class);
            String receives = messageUsers.stream().filter(d -> d.getMessageId().equals(m.getId())).map(d -> d.getReceiveUserName())
                    .collect(Collectors.joining(","));
            vm.setReceives(receives);
            vm.setCreateTime(DateTimeUtil.dateFormat(m.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/page/qywx", method = RequestMethod.POST)
    public RestResponse<PageInfo<QywxMessageRes>> pageQywxList(@RequestBody QywxMessagePageRequestVM model) {
        return RestResponse.ok(messageService.pageQywx(model));
    }


    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public RestResponse send(@RequestBody @Valid MessageSendVM model) {
        User user = getCurrentUser();
        List<User> receiveUser = userService.selectByIds(model.getReceiveUserIds());
        Date now = new Date();
        Message message = new Message();
        message.setTitle(model.getTitle());
        message.setContent(model.getContent());
        message.setCreateTime(now);
        message.setReadCount(0);
        message.setReceiveUserCount(receiveUser.size());
        message.setSendUserId(user.getId());
        message.setSendUserName(user.getUserName());
        message.setSendRealName(user.getRealName());
        List<MessageUser> messageUsers = receiveUser.stream().map(d -> {
            MessageUser messageUser = new MessageUser();
            messageUser.setCreateTime(now);
            messageUser.setReaded(false);
            messageUser.setReceiveRealName(d.getRealName());
            messageUser.setReceiveUserId(d.getId());
            messageUser.setReceiveUserName(d.getUserName());
            return messageUser;
        }).collect(Collectors.toList());
        messageService.sendMessage(message, messageUsers);
        return RestResponse.ok();
    }

    @RequestMapping(value = "/sendQywx", method = RequestMethod.POST)
    public RestResponse sendQywx(@RequestBody @Valid MessageSendVM model) {
       // List<User> users = newUserMapper.selectList(new LambdaQueryWrapper<User>().in(User::getQywxId, model.getReceiveUserIds()));

        List<String> receiveUserIds = model.getReceiveUserIds().stream().distinct().collect(Collectors.toList());

        // 保存记录
        QywxMessage qywxMessage = new QywxMessage()
                .setTitle(model.getTitle())
                .setContent(model.getContent())
                .setSendUserId(getCurrentUser().getId())
                .setReceiveUserCount(receiveUserIds.size())
                .setCreateTime(LocalDateTime.now());
        qywxMessageMapper.insert(qywxMessage);

        List<QywxMessageUser> qywxMessageUsers = new ArrayList<>();
        receiveUserIds.forEach(qywxId -> {
            qywxMessageUsers.add(
                    new QywxMessageUser()
                            .setMessageId(qywxMessage.getId())
                            .setReceiveUserQywxid(qywxId)
                            .setReaded(false)
                            .setCreateTime(LocalDateTime.now())
            );
        });
        qywxMessageUserService.saveBatch(qywxMessageUsers);

        return RestResponse.ok(
                qywxComponent.sendMsg(
                        new TextNotice()
                                .setTouser(String.join("|", receiveUserIds))
                                .setMsgtype(QywxMsgType.TEXT.getMsgtype())
                                .setEnable_id_trans(0)
                                .setAgentid(agentId)
                                .setEnable_duplicate_check(0)
                                .setDuplicate_check_interval(1800)
                                .setText(
                                        new TextNotice.Text()
                                                .setContent(String.format("%s\n\n%s", model.getTitle(), model.getContent()))
                                )
                )
        );
    }

}
